<template>
    <div class="inline-container">
        <template>
            <div class="el-input-number">
                <div class="el-input__decrease" @click="count(-1)">
                    <Icon name="minus" ></Icon>
                </div>
                <div class="el-input__increase" @click="count(1)">
                    <Icon name="plus" ></Icon>
                </div>
                <div class="el-input--outer">
                    <input type="text" class="el-input" :value="value" @input="handleInput($event)" @change="handleChange"
                        v-on="clearListeners($listeners)" v-bind="$attrs" />
                </div>
            </div>
        </template>
    </div>
</template>

<script>
import { defineComponent } from 'vue-demi'
import Icon from '../icon/index.vue';
export default defineComponent({
    name: "el-input-number",
    props: {
        value: {
            // 扩展 v-model 语法糖
            type: Number,
            default: 0
        },
    },
    methods:{
        handleChange(){
            this.$forceUpdate()
        }
    },
    setup(props, { emit }) {
        const handleInput = (e) => {
            // 处理非法输入
            const val = e.target.value;
            if(val == "") {emit("input",0);return;}
            if(isNaN(val) || Object.prototype.toString.call(val*1)!== "[object Number]") return;
            // 扩展 v-model 语法糖
            emit("input", val);
        };
        const clearListeners = ($listeners) => {
            // 不加下面这句的话，父组件的 @input事件也会被继承添加到当前input元素上
            // 所以，会造成触发两次 input 事件
            // 即 @input(event)=>{this.mes = $event}
            delete $listeners.input;
            return $listeners;
        };
        const count = (diff)=>{
            emit("input",props.value+diff)
        }
        return {
            handleInput,
            clearListeners,
            count
        };
    },
    components: { Icon }
})
</script>

<style lang="scss">
@import "./index.scss";
</style>